package com.symagic;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.badlogic.gdx.backends.android.AndroidApplication;
import com.example.android.BluetoothChat.BluetoothChatService;
import com.example.android.BluetoothChat.DeviceListActivity;
import com.symagic.game.MainGame;
import com.symagic.game.SymagicGame;

public class GameActivity extends AndroidApplication {

	private BluetoothChatService communicator;
	private Handler handler;
	private boolean isAttack = false;
	private String attackWay;
	public int damage;
	public SymagicGame gameClass;
	
	//message types
	public final static int INITIALIZE_DATA_MSG = 1;
	public final static int ATTACK_MSG = 2;
	
	// Intent request codes
	public final static int REQUEST_SEND_SYMBOL = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Intent intent = this.getIntent();

		// build the handler
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case BluetoothChatService.MESSAGE_STATE_CHANGE:
					switch (msg.arg1) {
					case BluetoothChatService.STATE_CONNECTED:
						Toast.makeText(getApplicationContext(), "Connected",
								Toast.LENGTH_SHORT).show();
						
						//send basic data to another player when game start
						sendBasicData();
						break;
					case BluetoothChatService.STATE_CONNECTING:
						Toast.makeText(getApplicationContext(), "Connecting",
								Toast.LENGTH_SHORT).show();
						break;
					case BluetoothChatService.STATE_LISTEN:
						Toast.makeText(getApplicationContext(), "Listening",
								Toast.LENGTH_SHORT).show();
						break;
					case BluetoothChatService.STATE_NONE:
						Toast.makeText(getApplicationContext(), "Not connect!",
								Toast.LENGTH_SHORT).show();
						break;
					}
					break;
				case BluetoothChatService.MESSAGE_WRITE:
					break;
				case BluetoothChatService.MESSAGE_READ:
					byte[] readBuf = (byte[]) msg.obj;
					// construct a string from the valid bytes in the buffer
					String readMsg = new String(readBuf, 0, msg.arg1);
					messageReadAction(readMsg);
					break;
				case BluetoothChatService.MESSAGE_DEVICE_NAME:
					// save the connected device's name
					Toast.makeText(
							getApplicationContext(),
							"Connected to "
									+ msg.getData().getString(
											BluetoothChatService.DEVICE_NAME),
							Toast.LENGTH_SHORT).show();
					break;
				case BluetoothChatService.MESSAGE_TOAST:
					Toast.makeText(
							getApplicationContext(),
							msg.getData().getString(BluetoothChatService.TOAST),
							Toast.LENGTH_SHORT).show();
					break;
				}

			}
		};

		// build the communicator
		communicator = new BluetoothChatService(this, handler);

		//See if creating a server or a client.	(SymagicActivity.SERVER for server)
		int ServerFlag;
		if ( ( ServerFlag = intent.getIntExtra(SymagicActivity.IS_SERVER, -1) ) == SymagicActivity.SERVER) {
			//Create server
			communicator.start();
		} else if( ServerFlag == SymagicActivity.CLIENT ){
			//Create client
			String address = intent.getExtras().getString(
					DeviceListActivity.EXTRA_DEVICE_ADDRESS);
			// Get the BLuetoothDevice object
			BluetoothDevice device = BluetoothAdapter.getDefaultAdapter()
					.getRemoteDevice(address);
			communicator.connect(device);

		}
        MainGame mainGame=new MainGame();
        mainGame.setActivity(this);
		this.initialize(mainGame, false);
         
	}
	
	protected void messageReadAction(String readMsg) {
		// TODO Auto-generated method stub
		String msg = readMsg;
		int msgType = 0;
		JSONObject JSONmsg = null;
		
		//act according to the message types
		try {
			JSONmsg = (JSONObject) new JSONTokener(msg).nextValue();
			msgType = JSONmsg.getInt("msgTypes");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		switch(msgType){
		case ATTACK_MSG:
			beAttacked(JSONmsg);
			break;
		case INITIALIZE_DATA_MSG:
			initialzeData(JSONmsg);
			break;
		}
	}

	private void initialzeData(JSONObject jSONmsg) {
		// TODO Auto-generated method stub
		JSONObject JSONmsg = jSONmsg;
		int jing = 0;
		int qi = 0;
		int shen = 0;
		JSONArray attribute = null;
		try {
			jing = JSONmsg.getInt("jing");
			qi = JSONmsg.getInt("qi");
			shen = JSONmsg.getInt("shen");
			attribute = JSONmsg.getJSONArray("attribute");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private void beAttacked(JSONObject jSONmsg) {
		// TODO Auto-generated method stub
		JSONObject JSONmsg = jSONmsg;
		 damage = 0;
		try {
			damage = JSONmsg.getInt("totalDamage");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		damage =1;
		gameClass.attackEffect(damage);
		
	}

	private void setAttack(boolean attack){
		isAttack = attack;
	}

	//Judge if user click the "attack" button in SymagicGame or not.
	public boolean isAttack(){	
		return isAttack;
	}
	public String attackway(char attackchar){ 
		switch(attackchar){
		case 'g':attackWay="gold.png";
		            break;
		case 'f':attackWay = "fire.png";
		            break;
		case 'e': attackWay ="earth.png";
		            break;
		case 'a': attackWay = "water.png";
		            break;
		case 'w' : attackWay = "wood.png";
		            break;
		default :  attackWay = "wrong";
		}
		
		return attackWay;
	}
	
	public BluetoothChatService getCommunicator(){
		return communicator;
	}
	
	protected void sendBasicData(){
		File file = new File("/data/data/com.symagic/player_basic_msg.txt");
		byte[] buffer = new byte[128];
		
		//read player_basic_msg
		InputStream inStream = null;
		try {
			inStream = new BufferedInputStream(new FileInputStream(file));
			try {
				int num = inStream.read(buffer);
				String str = new String(buffer);
				str.substring(0, num);
				buffer = new byte[num];
				buffer = str.getBytes();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			if (inStream != null)
				try {	
					inStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
		communicator.write(buffer);
	}
	
}
